<template>
  <div>
    <el-form ref="deptFormRef" v-loading="formLoading" :model="form" :rules="rules" label-width="80px">
      <el-row>
        <el-col v-if="form.parentId !== 0" :span="24">
          <el-form-item label="上级部门" prop="parentId">
            <el-tree-select
              v-model="form.parentId"
              :data="deptOptions"
              :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
              value-key="deptId"
              placeholder="选择上级部门"
              check-strictly
              @change="handleChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="部门名称" prop="deptName">
            <el-input v-model="form.deptName" placeholder="请输入部门名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="类别编码" prop="deptCategory">
            <el-input v-model="form.deptCategory" placeholder="请输入类别编码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="显示排序" prop="orderNum">
            <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="负责人" prop="leader">
            <el-select v-model="form.leader" placeholder="请选择负责人">
              <el-option v-for="item in deptUserList" :key="item.userId" :label="item.userName" :value="item.userId" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="部门状态">
            <el-radio-group v-model="form.status">
              <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div style="display: flex; justify-content: center; align-items: center;">
      <el-button type="primary" :loading="buttLoading" :disabled="buttLoading" @click="submitForm">确 定</el-button>
      <el-button :loading="buttLoading" :disabled="buttLoading" @click="emit('close')">取 消</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { listDept, addDept, updateDept } from '@/api/system/dept';
import { listUserByDeptId } from '@/api/system/user';
import { DeptForm, DeptQuery, DeptVO } from '@/api/system/dept/types';
import { UserVO } from '@/api/system/user/types';

interface DeptOptionsType {
  deptId: number | string;
  deptName: string;
  children: DeptOptionsType[];
}

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_normal_disable'));
const deptFormRef = ref<ElFormInstance>();

const emit = defineEmits(['close', 'success']);
const props = defineProps({
  rowList: {
    type: Array,
    default: () => []
  }
});

const initFormData: DeptForm = {
  deptId: undefined,
  parentId: undefined,
  deptName: undefined,
  deptCategory: undefined,
  orderNum: 0,
  leader: undefined,
  phone: undefined,
  email: undefined,
  status: '0',
  layer: undefined,
  deptParkId: undefined
};
const initData: PageData<DeptForm, DeptQuery> = {
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptName: undefined,
    deptCategory: undefined,
    status: undefined
  },
  rules: {
    parentId: [{ required: true, message: '上级部门不能为空', trigger: 'blur' }],
    deptName: [{ required: true, message: '部门名称不能为空', trigger: 'blur' }],
    orderNum: [{ required: true, message: '显示排序不能为空', trigger: 'blur' }],
    email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
    phone: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }]
  }
};
const data = reactive<PageData<DeptForm, DeptQuery>>(initData);

const { queryParams, form, rules } = toRefs<PageData<DeptForm, DeptQuery>>(data);

/** 新增按钮操作 */
const formLoading = ref(false);
const deptOptions = ref<DeptOptionsType[]>([]);
const handleAdd = async () => {
  formLoading.value = true;
  const res = await listDept().finally(() => { formLoading.value = false });
  // 判断res.data是否等于空，如果不为空则去除parentId为0的数据
  let dataArray = [];
  if (res.data) {
    res.data.forEach(function (data) {
      let parentId = data.parentId;
      // 判断parentId是否为0
      if (parentId != 0) {
        dataArray.push(data);
      }
    })
  } else {
    dataArray = res.data;
  }
  console.log('新增dataArray：', dataArray)
  const data = proxy?.handleTree<DeptOptionsType>(dataArray, 'deptId');
  console.log('新增data：', data)
  if (data) {
    deptOptions.value = data;
    if (props.rowList && props.rowList.deptId) {
      form.value.parentId = props.rowList?.deptId;
    }
    // dialog.showAdd = true;
    // dialog.title = '添加部门';
  }
};

const handleChange = (val) => {
  console.log('Selected value:', val);
  console.log('Selected label:', val);
  // 在这里处理选择变化的逻辑
  // 过滤出deptOptions中deptId=val的数据
  const selectedOption = deptOptions.value.find((option) => option.deptId === val);
  if (selectedOption) {
    // 获取选中项的deptName
    // 获取选中项的deptId
    // 获取选中项的parentId
    console.log(selectedOption)

    const layer = selectedOption.layer;
    const parkInfoId = selectedOption.parkInfoId;
    form.value.layer = layer
    form.value.deptParkId = parkInfoId;

    // 获取选中项的children
    // 获取选中项的ancestors
  }
};

/** 查询当前部门的所有用户 */
const deptUserList = ref<UserVO[]>([]);
async function getDeptAllUser(deptId: any) {
  if (deptId !== null && deptId !== '' && deptId !== undefined) {
    const res = await listUserByDeptId(deptId);
    deptUserList.value = res.data;
  }
}

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  deptFormRef.value?.resetFields();
};

/** 提交按钮 */
const buttLoading = ref(false);
const submitForm = () => {
  deptFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttLoading.value = true;
      await addDept(form.value).finally(() => { buttLoading.value = false });
      proxy?.$modal.msgSuccess('操作成功');
      emit('close');
      emit('success');
    }
  });
};

onMounted(() => {
  handleAdd();
  getDeptAllUser(form.value.deptId);
});
</script>

<style scoped lang="scss">

</style>
